import React, { useReducer, useEffect, useState } from "react";
import query from "../../api/query";
import AsyncStorage from "@react-native-async-storage/async-storage";

const InterviewSpeedContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "add_interviewSpeed":
      return [...state, action.payload];
    default:
      return state;
  }
};

export const InterviewSpeedProvider = ({ children }) => {
  const [InterviewSpeedList, dispatch] = useReducer(dataReducer, []);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    updateSpeedbyGroupNoLoading();
  }, []);

  // const getSpeedRecord = async () => {
  //   const token = await AsyncStorage.getItem("token");
  //   const interviewRecordByGroup = await query.get("/interviewspeed/group", {
  //     headers: { Authorization: token },
  //   });
  //   dispatch({ type: "fetch_init", payload: interviewRecordByGroup.data.data });
  // };

  // //第一版：只想更新今天的访谈进度，但是访谈时间可以变更，导致过去的访谈进度数据发生变化--------pass
  // //第二版：对新构造的访谈进度（表中存在就更新，表中不存在就创建），但是访谈时间变更有可能导致某一天没有访谈进度数据-----------pass
  // //第三版：拿到指定分组的所有访谈内容进而构造访谈进度，删除表中原有该组访谈进度，再依次根据新构造的访谈进度进行创建-----------简单明了，但随着数据的增多会变的很慢（待改进）
  // const updateInterviewSpeed = async (setIsLoading) => {
  //   try {
  //     //1、首先获取指定分组的所有访谈内容，根据日期构造访谈进度
  //     const token = await AsyncStorage.getItem("token");
  //     const result = await query.get("/interview/groupspeed/", {
  //       headers: { Authorization: token },
  //     });
  //     let interviewSpeed = result.data.data;
  //     //2、删除指定分组的所有访谈进度
  //     await query.delete("/interviewspeed/", {
  //       headers: { Authorization: token },
  //     });
  //     dispatch({ type: "fetch_init", payload: [] });
  //     //3、将第一步构造的访谈进度存表
  //     interviewSpeed.forEach(async (item) => {
  //       const createSpeed = await query.post("/interviewspeed/", item);
  //       dispatch({
  //         type: "add_interviewSpeed",
  //         payload: createSpeed.data.data,
  //       });
  //     });
  //     setIsLoading();
  //   } catch (err) {
  //     setIsLoading();
  //     console.log("更新访谈进度失败", err);
  //   }
  // };

  const updateSpeedbyGroup = async (setIsLoading) => {
    try {
      const token = await AsyncStorage.getItem("token");
      const result = await query.get("/interview/groupspeed/", {
        headers: { Authorization: token },
      });
      const sortSpeed = result.data.data.sort((a, b) => {
        return a.time < b.time ? 1 : -1;
      });
      dispatch({ type: "fetch_init", payload: sortSpeed });
      setIsLoading();
    } catch (err) {
      setIsLoading();
      console.log("更新访谈进度失败", err);
    }
  };

  const updateSpeedbyGroupNoLoading = async () => {
    try {
      setLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.get("/interview/groupspeed/", {
        headers: { Authorization: token },
      });
      const sortSpeed = result.data.data.sort((a, b) => {
        return a.time < b.time ? 1 : -1;
      });
      dispatch({ type: "fetch_init", payload: sortSpeed });
      setLoading(false);
    } catch (err) {
      setLoading(false);
      console.log("获取访谈进度失败", err);
    }
  };

  return (
    <InterviewSpeedContext.Provider
      value={{
        interviewSpeedList: InterviewSpeedList,
        loading,
        updateSpeedbyGroup,
      }}
    >
      {children}
    </InterviewSpeedContext.Provider>
  );
};

export default InterviewSpeedContext;
